<?php
namespace App\Handlers;


use App\Models\Stock;
use App\Services\StockService;
use Illuminate\Support\Facades\DB;


// 使用缓存
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;


class SwooleHandler
{
    private $key;

    protected $stock_list;

    protected $get_url;

    public function __construct()
    {
        $this->key = config('other.a_key');
        $this->host_name = config('other.host_name');

        $this->get_url = config('other.stock_url');
        $this->stock_list = StockService::getInstance()->getAll(2);
    }

    public function onStart($serv)
    {
    }

    public function OnConnect($serv, $fd, $from_id)
    {
    }

    public function OnClose($serv, $fd, $from_id)
    {
    }

    public function onReceive($serv, $fd, $from_id, $data)
    {

//
        if ($serv) {
            $ip = $serv->connection_info($fd)['remote_ip'];
        } else {
            $ip = request()->getClientIp();
        }

        // 获取ip
        $list['ip'] = $ip;
//
//         $t1 = microtime(true);
// //        $a = Stock::monitorCapStock();dd($a);
//         $data     = Stock::get_stock_real_time($this->stock_list, $this->get_url);
//         $data_cap = Stock::get_stock_real_time_cap($this->stock_list, $this->get_url);
//
//         foreach ( $data as $key => $vo ) {
//             $list[] = array_merge($vo, $data_cap[$key]);
//         }
//         $t2 = microtime(true);

        if ($serv) {
            return $serv->send($fd, $list);
            // return $serv->close($fd);
        } else {
            return $list;
        }

    }

}
